package com.yibo.interceptor;

import com.yibo.redis.RedisCommand;
import com.yibo.support.context.SpringContext;
import com.yibo.support.helper.Assert;
import com.yibo.support.helper.JsonHelper;
import com.yibo.support.helper.ObjectHelper;
import com.yibo.support.jwt.JWTUtils;
import com.yibo.support.pojo.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.yibo.support.constant.ApiUrlConstant.PUBLIC_URL;
import static com.yibo.support.constant.YBConstant.CLI_IP;
import static com.yibo.support.constant.YBConstant.YIBO_USER_REDIS_PREFIX_IP;
import static com.yibo.support.constant.YBConstant.YIBO_USER_REDIS_PREFIX_TOKEN;

//@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    @SuppressWarnings("unchecked")
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //接口地址
        String path = request.getServletPath();

        //是公开的
        if(path.contains(PUBLIC_URL)){
            return true;
        }

        //如果是系统内部调用，直接放权
        String auth = request.getHeader("Authorization");
        if(auth != null){
            JWTUtils.JWTResult ret = JWTUtils.getInstance().checkToken(auth);
            Assert.isTrue(ret.getMsg(),!ret.isStatus());
            return true;
        }

        String token = request.getHeader("token");
        //先校验token是否正确
        JWTUtils.JWTResult result = JWTUtils.getInstance().checkToken(token);
        if(!result.isStatus()){
            response.getWriter().write(JsonHelper.toJson(new Result<>(-1,result.getMsg(),null)));
            return false;
        }

        //再校验token是否过期
        String ip = request.getHeader(CLI_IP)+"";
        RedisCommand redisCommand = SpringContext.getBean(RedisCommand.class);
        Object ipUser = redisCommand.get(YIBO_USER_REDIS_PREFIX_IP+ip);
        Object tokenUser = redisCommand.get(YIBO_USER_REDIS_PREFIX_TOKEN+token);
        if(ObjectHelper.hasEmpty(ipUser,tokenUser)){
            redisCommand.remove(ip);
            redisCommand.remove(token);
            response.getWriter().write(JsonHelper.toJson(new Result(-120,"请先登录",null)));
            return false;
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
